package cn.myzf.fort.fortaccess.listener;


import cn.myzf.fort.access.accesscommon.event.ProcessOutputEvent;
import cn.myzf.fort.fortaccess.dto.H2Service;
import cn.myzf.fort.fortaccess.dto.SOCK5FORWARDLOGVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
@Slf4j
public class ProcessOutputListener {

    @Autowired
    private H2Service h2Service;
    @Autowired
    private RedissonClient redissonClient;


    @EventListener
    public void onProcessOutputEvent(ProcessOutputEvent event) {
        RLock s1 = redissonClient.getLock("s");
        s1.lock();
        String line = event.getLine();
        String sock5Foward = event.getSock5Foward();
        if (StringUtils.isNotBlank(line)){
            if (line.endsWith("Access denied")) {
                throw new IllegalStateException(String.format("开启 【%s】 代理开启失败，请检查ssh用户名密码是否正确!!!",sock5Foward));
            } else if (line.endsWith("Access granted")){
                log.info(String.format("授权成功,sock5代理已开启，服务器地址是【%s】",sock5Foward));
            }
       //日志写入h2数据库
           // Opening connection to oracle57.prd.db:1521 for forwarding from 127.0.0.1:62639
            if (line.startsWith("Opening connection to")) {
                try {
                    String[] s = line.split(" ");
                    SOCK5FORWARDLOGVo sock5FORWARDLOGVo = new SOCK5FORWARDLOGVo();
                    sock5FORWARDLOGVo.setREQID(UUID.randomUUID().toString());
                    sock5FORWARDLOGVo.setIp(InetAddress.getLocalHost().getHostAddress());
                    sock5FORWARDLOGVo.setSourceAddress(regex(s[3])[0]);
                    sock5FORWARDLOGVo.setSourcePort(regex(s[3])[1]);
                    sock5FORWARDLOGVo.setDestAddress(regex(s[7])[0]);
                    sock5FORWARDLOGVo.setDestPort(regex(s[7])[1]);
                    sock5FORWARDLOGVo.setOptTime(getNowDateString());
                    sock5FORWARDLOGVo.setForwardNode(sock5Foward);
                    h2Service.save(sock5FORWARDLOGVo);
                }catch (Exception e) {
                    log.error("记录h2日志错误,错误详情是"+e.getMessage());
                }
            }
        }
    }



    private String[] regex(String ap,String regex){
       return ap.split(regex);
    }

    private String[] regex(String ap){
        return regex(ap,":");
    }

    private String getNowDateString(String pattern) {
        Date dd=new Date();
        SimpleDateFormat sim=new SimpleDateFormat(pattern);
        return sim.format(dd);
    }
    private String getNowDateString(){
        return getNowDateString("yyyy-MM-dd HH:mm:ss");
    }


}
